package cn.rengy.web.framework.wxmp.profitsharing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import cn.rengy.lang.DataConverter;
import cn.rengy.lang.ResultEntity;
import cn.rengy.tpa.wxmp.profitsharing.AddReceiverDTO;
import cn.rengy.tpa.wxmp.profitsharing.ProfitSharingApi;
import cn.rengy.tpa.wxmp.profitsharing.ReceiverDTO;
import cn.rengy.web.framework.id.IdGenerator;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.wxmp.WxmpConstants;

/**
 * 分账接收人
 * @author rengy
 *
 */
@Service
public class WXProfitShareReceiverService {
	private static Logger logger = LoggerFactory.getLogger(WXProfitShareReceiverService.class);
	@Autowired(required = false)
	private RedisTemplate<Object, Object> redisTemplate;
	@Autowired
	private DbService dbService;
	@Autowired
	private IdGenerator idGenerator;
	
	@Autowired
	private DataConverter dataConverter;
	/**
	 * 分账接收方是否存在，不存在时新增
	 * @param rengy
	 */
	public void addOnNotExist(String mchKey,ProfitShareReceiverPO wXProfitShareReceiverPO) {
		WxProfitShareReceiverKey wxProfitShareReceiverKey=new WxProfitShareReceiverKey();
		wxProfitShareReceiverKey.setAccount(wXProfitShareReceiverPO.getAccount());
		wxProfitShareReceiverKey.setAppid(wXProfitShareReceiverPO.getAppid());
		wxProfitShareReceiverKey.setMch_id(wXProfitShareReceiverPO.getMch_id());
		wxProfitShareReceiverKey.setType(wXProfitShareReceiverPO.getType().toString());
		
		if(!redisTemplate.opsForSet().isMember(WxmpConstants.KEY_wxProfitShareReceiverCache, wxProfitShareReceiverKey)) {
			wXProfitShareReceiverPO.setId(idGenerator.nextId().toString());
			//新增到数据库
			this.dbService.updateBeanParameter("insert_wx_profit_share_receiver", wXProfitShareReceiverPO);
			//请求微信api
			AddReceiverDTO addReceiverDTO=new AddReceiverDTO();
			addReceiverDTO.setAppid(wXProfitShareReceiverPO.getAppid());
			addReceiverDTO.setMch_id(wXProfitShareReceiverPO.getMch_id());
			ReceiverDTO receiver=new ReceiverDTO();
			receiver.setAccount(wXProfitShareReceiverPO.getAccount());
			receiver.setCustom_relation(wXProfitShareReceiverPO.getCustom_relation());
			receiver.setName(wXProfitShareReceiverPO.getName());
			receiver.setRelation_type(wXProfitShareReceiverPO.getRelation_type());
			receiver.setType(wXProfitShareReceiverPO.getType());
			addReceiverDTO.setReceiver(receiver);
			
			ResultEntity r=ProfitSharingApi.addReceiver(dataConverter, mchKey, addReceiverDTO);
			//新增到redis
			if(r.isSuccess()) {
				redisTemplate.opsForSet().add(WxmpConstants.KEY_wxProfitShareReceiverCache, wxProfitShareReceiverKey);
			}
		}
		
	}
	
}
